/*
 *    Copyright © OpenAtom Foundation.
 *
 *    Licensed under the Apache License, Version 2.0 (the "License");
 *    you may not use this file except in compliance with the License.
 *    You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 *    Unless required by applicable law or agreed to in writing, software
 *    distributed under the License is distributed on an "AS IS" BASIS,
 *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *    See the License for the specific language governing permissions and
 *    limitations under the License.
 */

package com.inspur.edp.bef.engine.core.temptable;

import com.inspur.edp.bef.bizentity.common.SysnDboUtils;
import com.inspur.edp.bef.engine.entity.BaseTempTableInfo;
import com.inspur.edp.cef.designtime.api.element.GspElementDataType;
import com.inspur.edp.lcm.metadata.api.entity.GspMetadata;
import com.inspur.edp.lcm.metadata.api.entity.MetadataHeader;
import com.inspur.edp.lcm.metadata.cache.MetadataCacheManager;
import com.inspur.edp.lcm.metadata.cache.MetadataDistCacheManager;
import com.inspur.edp.lcm.metadata.cache.MetadataRtDistCache;
import com.inspur.edp.lcm.metadata.cache.RtCacheHandler;
import com.inspur.edp.lcm.metadata.common.context.RuntimeContext;
import com.inspur.edp.metadata.rtcustomization.api.CustomizationService;
import io.iec.edp.caf.commons.utils.SpringBeanUtils;
import io.iec.edp.caf.databaseobject.api.entity.*;
import io.iec.edp.caf.databaseobject.api.service.IDatabaseObjectRtService;

import java.io.Closeable;
import java.io.IOException;
import java.util.ArrayList;

import static jdk.nashorn.internal.runtime.regexp.joni.Syntax.Java;

public class TempTableManager implements Closeable {
    private boolean closed = false;
    private BaseTempTableInfo baseTempTableInfo;
    private GspMetadata gspMetadata = new GspMetadata();;
    private DatabaseObjectTempTable dbo;
    private TempTableContext tempTableContext;

    private IDatabaseObjectRtService databaseObjectRtService = SpringBeanUtils.getBean(IDatabaseObjectRtService.class);
    public TempTableManager(String code, String name){
        initMetadata(code, name);
    }

    private void initMetadata(String code, String name){
        String beId = java.util.UUID.randomUUID().toString();
        baseTempTableInfo = new BaseTempTableInfo(code, name, beId);
        MetadataHeader metadataHeader = new MetadataHeader();
        metadataHeader.setId(beId);
        String assembley = java.util.UUID.randomUUID().toString();
        baseTempTableInfo.getBusinessEntity().setGeneratingAssembly(assembley);
        baseTempTableInfo.getBusinessEntity().setDotnetGeneratingAssembly(assembley);
        baseTempTableInfo.getBusinessEntity().setIsUseNamespaceConfig(true);
        metadataHeader.setCode(baseTempTableInfo.getCode());
        metadataHeader.setName(baseTempTableInfo.getName());
        metadataHeader.setType("GSPBusinessEntity");
        gspMetadata.setHeader(metadataHeader);
    }



    public void addColumnInfo(String columnName, GspElementDataType gspElementDataType, boolean isPrimaryKey, boolean isRequire, boolean isNull){
        addColumnInfo(columnName, gspElementDataType, isPrimaryKey, isRequire, isNull, 0, 0);
    }

    public void addColumnInfo(String columnName, GspElementDataType gspElementDataType, boolean isPrimaryKey, boolean isRequire, boolean isNull, int length, int precision){
        baseTempTableInfo.addColumn(columnName, gspElementDataType, isPrimaryKey, isRequire, isNull, length, precision);
    }

    public String getBeId(){
        return gspMetadata.getHeader().getId();
    }

    public TempTableContext createTempTable() {
        baseTempTableInfo.initBusinessEntity();
        gspMetadata.setContent(baseTempTableInfo.getBusinessEntity());
        createTempDbo();
        String metadataCacheKey = RtCacheHandler.getMetadataCacheKey(gspMetadata.getHeader().getId(), RuntimeContext.getLanguage());
        MetadataDistCacheManager.put(gspMetadata.getHeader().getId(), gspMetadata, null);
        MetadataDistCacheManager.put(metadataCacheKey, gspMetadata, null);
        MetadataRtDistCache.put(gspMetadata.getHeader().getId(), gspMetadata, null);
        MetadataRtDistCache.put(metadataCacheKey, gspMetadata, null);
        tempTableContext = databaseObjectRtService.creatTempTables(dbo.getId());
        return tempTableContext;
    }

    private void createTempDbo(){
        dbo = SysnDboUtils.createTempDbo(baseTempTableInfo.getBusinessEntity().getMainObject());
        dbo.setCode(this.baseTempTableInfo.getCode());
        dbo.setType(DatabaseObjectType.TempTable);
        databaseObjectRtService.addDatabaseObjectContent(dbo);
        baseTempTableInfo.getBizEntityObject().setRefObjectName(dbo.getId());
        TempBEInfoManager.getInstance().addItem(baseTempTableInfo.getBusinessEntity().getGeneratedConfigID(), getBeId());
    }

    public void dropTempTable() {
        if(!closed){
            CustomizationService customizationService = SpringBeanUtils.getBean(CustomizationService.class);
            java.util.List<String> metadataIds = new ArrayList();
            metadataIds.add(gspMetadata.getHeader().getId());
            customizationService.removeCacheByMetadataIds(metadataIds);
            databaseObjectRtService.dropTempTable(tempTableContext, dbo.getId());
            databaseObjectRtService.clearDatabaseObjectContentById(dbo.getId());
            TempBEInfoManager.getInstance().removeItem(gspMetadata.getHeader().getNameSpace() + "." + baseTempTableInfo.getCode());
            closed = true;
        }
    }

    @Override
    public void close() throws IOException {
        dropTempTable();
    }
}
